<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false" labelWidth="130" />
    <FilterTable ref="table" :columns="columns" :dataSource="tableList" height="auto" :isSelectColumn="false" :onColumnsChange="columns => (this.columns = columns)">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" @click="addHandle()" icon="el-icon-plus" v-if="ishide">新 增</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="isaddCar" :title="'新增车辆'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <selectCar :carData="carData" @close="carcloseHandler" />
    </BaseDialog>
    <div style="height:47px;"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)">关 闭</el-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)" :disabled="isOpen">提 交</multiuse-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 3)">保 存</multiuse-button>
      <!-- <el-button @click="closeDrawer(2)" type="primary">提 交</el-button>
      <el-button @click="closeDrawer(3)" type="primary">保 存</el-button> -->
    </div>
  </div>
</template>
<script>
import { getAmount, getDiscount, getDiscountDetails, saveOrder, getNotPage, getDealerAddress, getDetail } from '@/api/dealerSale/OrderManagement/afOrderSubmission/index.js';
import { dictionary } from '@/utils/dictMixin';
import Cookies from 'js-cookie';
import moment from 'moment';
import selectCar from './selectCar';
export default {
  data() {
    this.saveData = null;
    this.Amount = null;
    this.singleRebateFuelTotalAmount = null;
    this.buildRebateFuelTotalAmount = null;
    this.singleRebateEnergyTotalAmount = null;
    this.buildRebateEnergyTotalAmount = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      isaddCar: false,
      carData: {},
      json: {},
      isDiscount: false,
      DiscountData: {},
      TotalAmount: '',
      singleRebateFuelAmount: '',
      buildRebateFuelAmount: '',
      singleRebateEnergyAmount: '',
      buildRebateEnergyAmount: '',
      dealerCode: Cookies.get('ownerCode'),
      isOpen: false,
      ishide: true
    };
  },
  components: {
    selectCar
  },
  props: ['rowData'],
  created() {
    // this.getAmountDetail(this.dealerCode);
    if (this.rowData.appOrderNo) {
      this.ishide = false;
    } else {
      this.ishide = true;
    }
    this.getDetail(this.rowData);
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  mixins: [dictionary],
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息'
        },

        {
          type: 'INPUT',
          label: '订货单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM')
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('6043'),
          initialValue: 60431001
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: [{ text: '调货订单', value: 60061007 }],
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          change: p => {
            if (p) {
              this.formList.find(x => x.fieldName == 'orderDetailType').itemList = [];
              this.formList.find(x => x.fieldName == 'orderDetailType').initialValue = '';
              this.getNotPage(p);
            } else {
              this.formList.find(x => x.fieldName == 'orderDetailType').itemList = [];
              this.formList.find(x => x.fieldName == 'orderDetailType').initialValue = '';
            }
          }
        },
        {
          type: 'SELECT',
          label: '订单细分类型',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('6004'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },

        {
          type: 'BREAK_SPACE',
          label: '车辆信息'
        }
      ];
    },
    createdTable() {
      let hide = this.ishide;
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)} disabled={!hide}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          width: 100,
          editRequired: true,
          editPattern: /^[1-9]\d*$/,
          summation: true,
          defaultEditable: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          onInput: (index, data) => {
            this.changeNum(index, data);
          }
        },
        {
          title: '收车地址',
          dataIndex: 'addressId',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return (
              <el-select
                size="mini"
                v-model={p.row.addressId}
                placeholder="请选择"
                onChange={value => {
                  p.row.addressId = value;
                }}
              >
                {p.row.addressList.map(item => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            );
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'text'
        }
      ];
    },
    // 新增车辆
    addHandle() {
      this.$refs.from.SUBMIT_FORM();
      if (this.saveData) {
        let json = JSON.parse(JSON.stringify(this.saveData));
        json.dealerCode = this.dealerCode;
        this.carData = json;
        this.isaddCar = true;
        this.saveData = null;
      }
    },
    changeHandle(val) {
      this.saveData = val;
    },
    async getNotPage(orderType) {
      let list = await getNotPage({ orderType: orderType, isAvailable: 10041001 });
      this.formList.map(x => {
        if (x.fieldName == 'orderDetailType') {
          x.itemList = list.data.map(x => ({ text: x.subName, value: x.subId }));
        }
      });
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close');
      } else if (type == 2) {
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning'
          });
          return;
        }
        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {
          let json = JSON.parse(JSON.stringify(this.saveData));
          let arr = this.tableList;
          console.log(json);
          let is = false;
          arr.map(x => {
            if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
              is = true;
            }
          });
          console.log(json);
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning'
            });
            return;
          }
          json.detailDTOList = arr;
          json.id = this.rowData.id;
          json.saveType = 'sub';
          json.orderMonth = json.orderYearMonth.split('-')[1];
          json.orderYear = json.orderYearMonth.split('-')[0];
          console.log(json);
          let res = await saveOrder(json);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success'
            });
            this.$emit('close', json);
          } else {
            this.saveData = null;
          }
        }
      } else {
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning'
          });
          return;
        }
        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {
          let json = JSON.parse(JSON.stringify(this.saveData));
          let arr = this.tableList;
          let is = false;
          arr.map(x => {
            if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
              is = true;
            }
          });
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning'
            });
            return;
          }
          json.detailDTOList = arr;
          json.id = this.rowData.id;
          json.orderStatus = 60431001;
          json.orderMonth = json.orderYearMonth.split('-')[1];
          json.orderYear = json.orderYearMonth.split('-')[0];
          let res = await saveOrder(json);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success'
            });
            this.$emit('close', json);
          } else {
            this.saveData = null;
          }
        }
      }
    },
    async carcloseHandler(val, carData) {
      this.isaddCar = false;
      if (val) {
        let is = false;
        this.tableList.map(x => {
          if (x.productCode == val.productCode) {
            is = true;
          }
        });
        if (!is) {
          // await this.getAddress(val)
          await this.getDisecount(val, carData);
        } else {
          // 提示
          this.$notify({
            title: '警告',
            message: '列表已有该车辆',
            type: 'warning'
          });
          return;
        }
      }
    },
    Discountclose() {
      this.isDiscount = false;
    },
    // 加载折扣信息
    async getDisecount(data, carData) {
      // let res = await getDiscount({
      //   saveType: 'DLR',
      //   orderType: carData.orderType,
      //   orderDetailType: carData.orderDetailType,
      //   transportType: carData.transportType,
      //   isRebate: carData.isRebate,
      //   detailDTOList: [
      //     {
      //       modelCode:data.modelCode,
      //       singleAmount: data.basicPrice || 100000,
      //       powerType: data.powerType,
      //       optionId: data.optionId,
      //       optionCode: data.optionCode,
      //       subsidyAmount:data.subsidyAmount,
      //     }
      //   ]
      // });
      // 使用返利总金额
      // 车辆返利总额 与返利池余额比较
      // 如果大于返利池余额 则直接使用返利池余额
      // 返利池剩余0
      // 如果小于返利池余额 使用车辆返利总额
      // 返利池剩余为返利池剩余-车辆返利
      let obj = (await getDealerAddress({ dealerCode: this.dealerCode, powerType: data.powerType })).data.map(x => ({
        text: x.detaildAddress,
        value: x.addressId,
        addressProperty: x.addressProperty
      }));
      let json = Object.assign({}, data, carData);
      json.addressList = obj;
      let str = false;
      obj.map(x => {
        if (x.addressProperty == 60351001) {
          str = x.value;
        }
      });
      json.addressId = str ? str : obj[0].value;
      console.log(json, 'json');
      this.table.EXECUTE_INSERT([json]);
      // 计算单车返利总金额和建店返利增金额 实付总金额
    },
    changeNum(index, data) {
      console.log(index, data, '改变数量');
      let num = '';
      let str = '';
      for (let i in index) {
        num = index[i];
        console.log(i, 'i');
        str = i.split('|')[0];
      }
      let Rep = /^[1-9]\d*$/;
      if (num > 10000000000) {
        this.$notify({
          title: '警告',
          message: '输入数量过大',
          type: 'warning'
        });
        return;
      }
    },
    // 获取详情
    async getDetail(data) {
      let res = await getDetail({ orderId: data.id });
      for (let i in res.data) {
        this.formList.map(x => {
          if (i == x.fieldName) {
            x.initialValue = res.data[i];
          }
        });
      }
      let list = (await getDealerAddress({ dealerCode: this.dealerCode, powerType: 60081002 })).data.map(x => ({ text: x.detaildAddress, value: x.addressId, addressProperty: x.addressProperty }));
      this.getNotPage(res.data.orderType);
      res.data.detail.map(x => {
        x.addressList = list || [];
      });

      // 驳回不让提交 2021-5-17 17:14:45 调货单提报 修改 驳回可以提交
      if (this.rowData.orderStatus == 60431002) {
        this.isOpen = false;
      } else {
        this.isOpen = false;
      }
      this.tableList = res.data.detail || [];
    }
  }
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
